<template>
    <div>
        <Form :label-width="100" ref="formInline" :model="formInline">
            <div v-if="switchFlag">
                <Row :gutter="16" class="query-form2" >
                    <i-col span="8">
                        <FormItem label="办公室邮箱：">
                            <Input  class='' type='text' v-model='formInline.officeMail'></Input>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="负责人：">
                            <Input  class='' type='text' v-model='formInline.ownerName'></Input>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="填报人：">
                            <Input  class='' type='text' v-model='formInline.createUserName'></Input>
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16" class="query-form2" >
                    <i-col span="8">
                        <FormItem label="企业名称：">
                            <cascaderDom ref="queryOrgCascader2" @setOrgInfo="setOrgId2"
                                         :orgTree="true"></cascaderDom>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="二级集团：">
                            <Select v-model="formInline.twoCompanyId" filterable>
                                <Option v-for="item in twoLevelOrgList" :value="item.orgId" :key="item.orgId">{{ item.orgName }}</Option>
                            </Select>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <div style="float: right;">
                            <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reseter">重置</Button>
                            <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text" >收起<Icon type="ios-arrow-up" /></Button>
                        </div>
                    </i-col>
                </Row>
            </div>
            <div v-else>
                <Row :gutter="16" class="query-form2" >
                    <i-col span="8">
                        <FormItem label="办公室邮箱：">
                            <Input  class='' type='text' v-model='formInline.officeMail'></Input>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="负责人：">
                            <Input  class='' type='text' v-model='formInline.ownerName'></Input>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <div style="float: right;">
                            <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reseter">重置</Button>
                            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text" >展开<Icon type="ios-arrow-down"/></Button>
                        </div>
                    </i-col>
                </Row>
            </div>
        </Form>
        <Row type="flex" justify="start" class="query-form">
            <i-col>
                <Button icon="md-add" class="ivu-btn-add" @click="addInfo">新增</Button>
            </i-col>
        </Row>
        <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns" no-data-text="没有查询到相关数据！"
               :data="infos" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
        <Row type="flex" justify="end" >
            <i-col>
                <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                      @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </i-col>
        </Row>
        <Modal v-model="modal1" width="800" :mask-closable="false" :title="'邮箱管理' + titleName">
            <Form ref="formCustom" :model="formData" :rules="ruleCustom" label-position="top">
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="企业名称：" prop="companyName">
                            <!--                            <Input suffix="ios-search" placeholder="请选择被检查单位" v-model="formData.companyName" readonly @on-focus="openOrgModal"/>-->
                            <orgDom ref="orgDom" @setOrgInfo="setOrgId3" :orgInfo="{name: formData.companyName}"></orgDom>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="所属二级集团：">
                            <Input v-model="formData.twoCompanyName" readonly/>
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="办公室邮箱：" prop="officeMail">
                            <Input v-model="formData.officeMail" />
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="负责人：" prop="ownerId">
                            <userDom @setUserInfo="setUserInfo" :userInfo="{userName: currentUser.userName}"></userDom>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="联系电话：" prop="phoneNumber">
                            <Input v-model="formData.phoneNumber" />
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="填报人：" prop="createUserName">
                            <Input v-model="formData.createUserName" readonly/>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="填报人电话：">
                            <Input v-model="formData.createPhoneNumber" />
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button @click="saveInfo" class="ivu-btn-save" :loading="buttonLoading">确定</Button>
                <Button @click="modal1 = false" class="ivu-btn-cancel" >取消</Button>
            </div>
        </Modal>
        <Modal v-model="modal2" width="800" :mask-closable="false" title="邮箱管理详情">
            <Form :model="formData">
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="企业名称：" >
                            {{formData.companyName}}
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="所属二级集团：">
                            {{formData.twoCompanyName}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16" class="code-row-bg2">
                    <i-col span="24">
                        <FormItem label="办公室邮箱：" >
                            {{formData.officeMail}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16">
                    <i-col span="12">
                        <FormItem label="负责人：">
                            {{formData.ownerName}}
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="联系电话：">
                            {{formData.phoneNumber}}
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16" class="code-row-bg2">
                    <i-col span="12">
                        <FormItem label="填报人：" >
                            {{formData.createUserName}}
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="填报人电话：" >
                            {{formData.createPhoneNumber}}
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button @click="modal2 = false" class="ivu-btn-cancel" >取消</Button>
            </div>
        </Modal>
        <Modal title="公司列表" :transfer=false v-model="modal3" :width=1000 footer-hide>
            <Form :label-width="110" ref="formInline2" :model="formInline2">
                <Row :gutter="16" class="query-form2">
                    <i-col span="8">
                        <FormItem label="公司名称：">
                            <Input v-model="formInline2.orgName" type="text"/>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="组织机构级别：">
                            <Select filterable v-model="formInline2.orgLevel"  @on-open-change="selectCodingSort"  >
                                <Option v-for="item in orgLevelList" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                            </Select>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <div style="float: right;">
                            <Button class="ivu-btn-query" icon="md-search" @click="queryOrg" style="margin-right: 10px">查询</Button>
                            <Button @click="resetOrg" class="ivu-btn-reset">重置</Button>
                        </div>
                    </i-col>
                </Row>
            </Form>
            <Table row-key='orgId' ref='table2' height="400" :loading="loading2" no-data-text="没有查询到相关数据!" border @on-select="selectionTable" @on-selection-change="changeTable"
                   :columns="orgColumn" :load-data="handleLoadData" width="100%" :data="orgDatas" size="small">
            </Table>
        </Modal>
    </div>
</template>

<script>

    var cascaderDom = () => import('@/components/cascader-dom.vue');;
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {Api} from '@/api/index.js';
    import userDom from "@/views/safe/assessment/inputUser.vue";
    import orgDom from "@/components/input-org.vue";

    export default {
        components:{
            userDom,
            cascaderDom,
            orgDom
        },
        name: "mailConfig",
        data(){
            const validateMail = (rule, value, callback) => {
                if(!this.formData.officeMail) {
                    return callback(new Error('办公室邮箱不能为空'));
                } else if(!/^[a-zA-Z0-9_-]+@bbmg.com.cn$/.test(this.formData.officeMail)) {
                    callback('办公室邮箱格式不正确');
                } else {
                    callback();
                }
            };
            const validatePhone = (rule, value, callback) => {
                if(!this.formData.phoneNumber) {
                    return callback(new Error('手机号不能为空'));
                } else if(!/^1[345789]\d{9}$/.test(this.formData.phoneNumber)) {
                    callback('手机号格式不正确');
                } else {
                    callback();
                }
            };
            return{
                switchFlag: false,
                isUpdate: false,
                currentUser: sessionStorage('userId').getObject('userId'),
                modal1: false,
                modal2: false,
                modal3: false,
                titleName: '',
                formInline: {},
                formInline2: {},
                loading: false,
                buttonLoading: false,
                tableHeight: '',
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                ruleCustom: {
                    companyName: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    officeMail: [
                        {
                            required: true,
                            // validator: validateMail,
                            // message: '请输入正确格式，例xxxx@bbmg.com.cn',
                            message: ' ',
                            trigger: 'blur,change'
                        }
                    ],
                    ownerId: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    phoneNumber: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    mobileNumber: [
                        {
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                },
                formData: {},
                columns: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        title: '企业名称',
                        align: 'center',
                        key: 'companyName',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.companyName || '--')
                            ]);
                        }
                    },
                    {
                        title: '所属二级集团',
                        align: 'center',
                        key: 'twoCompanyName',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.twoCompanyName || '--')
                            ]);
                        }
                    },
                    {
                        title: '办公室邮箱',
                        align: 'center',
                        key: 'officeMail',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.officeMail || '--')
                            ]);
                        }
                    },
                    {
                        title: '负责人',
                        align: 'center',
                        key: 'ownerName',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.ownerName || '--')
                            ]);
                        }
                    },
                    {
                        title: '联系电话',
                        align: 'center',
                        key: 'phoneNumber',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.phoneNumber || '--')
                            ]);
                        }
                    },
                    {
                        title: '填报人',
                        align: 'center',
                        key: 'createUserName',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.createUserName || '--')
                            ]);
                        }
                    },
                    {
                        title: '填报人电话',
                        align: 'center',
                        key: 'createPhoneNumber',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.createPhoneNumber || '--')
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        key: 'action',
                        align: 'center',
                        fixed: 'right',
                        minWidth: 160,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.modal2 = true;
                                            this.updateInfo(params.row);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.modal1= true;
                                            this.updateInfo(params.row);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        color: 'red',
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteInfo(params.row);
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    },
                ],
                infos: [],
                twoLevelOrgList: [],
                orgDatas: [],
                orgColumn:[
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center',
                    },
                    {
                        title: '组织机构名称',
                        minWidth: 200,
                        align: 'left',
                        key: 'orgName',
                        tree:true
                    },
                    {
                        title: '组织机构级别',
                        width: 150,
                        align: 'center',
                        key: 'orgLevel',
                        render:(h, params) => {
                            return h('span', this.orgLevelMap[params.row.orgLevel]);
                        }
                    },
                ],

            }
        },
        mounted(){
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.queryTwoLevelOrg();
            this.query();
        },
        watch: {
            "modal1": function (qw, er) {
                if(!qw){
                    this.formData = {};
                    setTimeout(() => {
                        this.$refs.orgDom.resetCurrentOrg();
                    }, 300);
                }
            },
            'modal3': function(qw,er){
                if(!qw){
                    this.formInline2.orgName = '';
                    this.formInline2.orgLevel = '';
                }
            },
        },
        methods: {
            query(){
                this.loading = true;
                let data = {
                    startPage: this.pagedata.currentPage,
                    pageSize: this.pagedata.pageSize,
                }
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.$http.get(Api.mailConfig, {
                    params: data
                }).then(function(res){
                    this.infos = res.data.data;
                    this.pagedata.total = res.data.totalSize;
                    this.loading = false;
                }, function(res){
                    this.$Message.error('请求失败');
                    this.loading = false;
                });
            },
            reseter(){
                this.formInline = {};
                setTimeout(() => {
                    this.$refs.queryOrgCascader2.resetCurrentOrg();
                }, 100);
                this.query();
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            addInfo(){
                this.titleName = '新增';
                this.isUpdate = false;
                this.formData = {
                    orgName: this.currentUser.orgName,
                    twoLevelOrgName: this.currentUser.twoLevelOrgName,
                    ownerName: this.currentUser.userName,
                    ownerId: this.currentUser.userId,
                    createUserName: this.currentUser.userName,
                    createPhoneNumber: this.currentUser.mobileNumber,
                    phoneNumber: this.currentUser.mobileNumber,
                };
                this.modal1 = true;
            },
            updateInfo(row){
                this.isUpdate = true;
                let thatRow = row;
                this.formData = thatRow;
                this.formData.updateUserId = this.currentUser.userId;
                setTimeout(() => {
                    this.$refs.orgDom.setCurrentOrg();
                }, 300);
                this.titleName = "修改";
            },
            saveInfo(){
                this.$refs['formCustom'].validate((valid) => {
                    if(valid) {
                        this.buttonLoading = true;
                        if(this.isUpdate){
                            this.$http.put(Api.mailConfig, this.formData).then(function(response){
                                this.buttonLoading = false;
                                this.modal1 = false;
                                this.query();
                                this.$Message.success({  content: '保存成功', duration: 4 });
                            });
                        }else{
                            this.$http.get(Api.checkMailOrg, {
                                params: {orgId: this.formData.companyId}
                            }).then(function(res){
                                if(res.data.data > 0){
                                    this.$Message.error('请勿新增重复机构');
                                    this.buttonLoading = false;
                                }else{
                                    this.$http.post(Api.mailConfig, this.formData).then(function(response){
                                        this.buttonLoading = false;
                                        this.modal1 = false;
                                        this.query();
                                        this.$Message.success({  content: '保存成功', duration: 4 });
                                    });
                                }
                            }, function(res){
                                this.$Message.error('检查组织机构是否重复出现异常');
                                this.buttonLoading = false;
                            });
                        }
                    }
                })
            },
            deleteInfo(row){
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该条信息</p>',
                    okText: '确认',
                    onOk: () => {
                        this.$http.delete(Api.mailConfig, {params:{
                                id: row.id,
                                updateUserId: this.currentUser.userId
                            }}).then((res) => {
                            this.$Message.success({content:'删除成功',duration: 4});
                            this.query();
                        })
                    },
                    cancelText: '取消'
                });
            },
            setUserInfo(data){
                this.formData.ownerName = data.userName;
                this.formData.ownerId = data.userId;
                this.formData.phoneNumber = data.mobileNumber
            },
            setOrgId(orgId) {
                this.$http.get(Api.mailConfig +'/towCompanyOrg', {params: { orgId: orgId}} ).then(res => {
                    if(res.data.status == 200){
                        if(res.data.data!=null){
                            this.$set(this.formData, 'twoCompanyName', res.data.data.orgName);
                            this.$set(this.formData, 'twoCompanyId', res.data.data.orgId);
                        }
                    }else{
                        this.$Message.error('所属二级集团获取失败');
                    }
                });
            },
            setOrgName(data) {
                this.formData.orgName = data;
            },
            switchQuery(flag){
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = this.tableHeight + 44;
                } else {
                    this.tableHeight = this.tableHeight - 44;
                }
            },
            queryTwoLevelOrg(){
                this.$http.get(Api.twoPlusFourReceipt + '/twoLevelOrg').then((res) => {
                    if(res.data.status == 200){
                        this.twoLevelOrgList = res.data.data;
                    }
                }).catch(e => {
                    this.$Message.error("附件删除失败");
                });
            },
            setOrgId2(data){
                this.formInline.companyId = data[data.length - 1];
            },
            setOrgId3(data){
                this.formData.companyId = data.orgId;
                this.formData.companyName = data.orgName;
                this.setOrgId(data.orgId);
            },
            openOrgModal(){
                this.modal3 = true;
                this.getOrgInfo();
            },
            selectionTable(selection, row){
                this.$set(this.formData, 'companyId', row.orgId);
                this.$set(this.formData, 'companyName', row.orgName);
                this.setOrgId(row.orgId);
                this.modal3 = false;
            },
            getOrgInfo(){
                this.$http.get(Api.queryOrgDetailById + "/" + sessionStorage('userId').getObject('userId').companyId).then(res => {
                    this.orgDatas = [];
                    let temp = {};
                    temp._loading = false;
                    temp.children = [];
                    temp.orgName = res.data.data.orgName;
                    temp.orgId = res.data.data.orgId;
                    this.orgDatas.push(temp);
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            handleLoadData (item, callback) {
                setTimeout(() => {
                    this.$http.get(Api.queryOrg, {
                        params: {
                            parentId: item.orgId,
                            codeAffordIf : 0
                        }
                    }).then(res => {
                        if(res.data.data.length !== 0) {
                            res.data.data.map(i => {
                                if(i.orgLevel != '0200100005000000007'){
                                    i._loading = false;
                                    i.children = [];
                                }
                            })
                            item.children = res.data.data;
                            callback(item.children);
                        } else {
                            delete item['_loading'];
                            item.children=[];
                            callback([]);
                        }
                    }).catch(e => {
                        this.$Message.error('请求失败');
                    })
                }, 2000);
            },
        }
    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';

</style>
